package net.esj.basic.pojo.proxy;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
import net.esj.basic.pojo.AbstractPojo;

public class PojoProxyFactory {

	private static PojoProxyFactory _instance;
	
	public <T> T create(T t,Class<T> clazz,MethodFilter filter,MethodHandler handler) throws InstantiationException, IllegalAccessException, InvocationTargetException{
		ProxyFactory factory=new ProxyFactory();
		factory.setSuperclass(clazz);
		factory.setFilter(filter);
		factory.setInterfaces(new Class[]{PojoProxy.class});
		
		Class<T> c = factory.createClass();
		T newt = c.newInstance();
		if(t==null){
			return t;
		}
		((AbstractPojo)newt).self = (AbstractPojo) t;
		((AbstractPojo)newt).pojoClass = clazz;
		BeanUtils.copyProperties(newt, t);
		((ProxyObject)newt).setHandler(handler);
		return newt;
	}
	
	public static PojoProxyFactory getInstance(){
		if(_instance==null){
			_instance = new PojoProxyFactory();
		}
		return _instance;
	}
}
